package com.mashiro.system.controller;

import com.mashiro.common.annotation.Log;
import com.mashiro.common.core.controller.BaseController;
import com.mashiro.common.core.domain.AjaxResult;
import com.mashiro.common.core.domain.entity.SysRole;
import com.mashiro.common.core.domain.model.LoginUser;
import com.mashiro.common.core.page.TableDataInfo;
import com.mashiro.common.enums.BusinessType;
import com.mashiro.common.utils.SecurityUtils;
import com.mashiro.common.utils.poi.ExcelUtil;
import com.mashiro.system.domain.MoeProject;
import com.mashiro.system.domain.MoeTask;
import com.mashiro.system.domain.status.MoeProjectStatus;
import com.mashiro.system.service.IMoeProjectService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目Controller
 *
 * @author mashiro
 * @date 2023-04-15
 */
@RestController
@RequestMapping("/system/project")
public class MoeProjectController extends BaseController {
    @Resource
    private IMoeProjectService moeProjectService;

    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(MoeProject moeProject) {
        startPage();
        AtomicBoolean isAdmin = new AtomicBoolean(false);
        AtomicBoolean isManager = new AtomicBoolean(false);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        roles.forEach(sysRole -> {
            if (11L == sysRole.getRoleId()){
                isManager.set(true);
            }else if (1L == sysRole.getRoleId() || 10L == sysRole.getRoleId()){
                isAdmin.set(true);
            }
        });
        if (!isAdmin.get()){
            if (isManager.get()){
                moeProject.setManagerId(SecurityUtils.getUserId());
            }
        }
        List<MoeProject> list = moeProjectService.selectMoeProjectList(moeProject);
        return getDataTable(list);
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MoeProject moeProject) {
        List<MoeProject> list = moeProjectService.selectMoeProjectList(moeProject);
        ExcelUtil<MoeProject> util = new ExcelUtil<>(MoeProject.class);
        util.exportExcel(response, list, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(moeProjectService.selectMoeProjectById(id));
    }

    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MoeProject moeProject) {
        return toAjax(moeProjectService.insertMoeProject(moeProject));
    }

    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MoeProject moeProject) {
        return toAjax(moeProjectService.updateMoeProject(moeProject));
    }

    /**
     * 删除项目(批量)
     */
    @PreAuthorize("@ss.hasPermi('system:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult batchRemove(@PathVariable Long[] ids) {
        int i = moeProjectService.deleteMoeProjectByIds(ids);
        if (i > 0) {
            return success();
        } else {
            return error();
        }

    }

    /**
     * 获取已分配占比
     *
     * @param id 项目主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/getAllocatedProportion/{id}")
    public AjaxResult getAllowableProportion(@PathVariable("id") Long id) {
        Integer proportion = moeProjectService.getAllocatedProportion(id);
        if (Objects.isNull(proportion)) {
            return success(0);
        } else {
            return success(proportion);
        }
    }

    /**
     * 获取项目进度情况
     *
     * @param id 项目主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/getProjectScheduleDetails/{id}")
    
    public AjaxResult getProjectScheduleDetails(@PathVariable("id") Long id) {
        Integer scheduleDetails = moeProjectService.getProjectScheduleDetails(id);
        if (Objects.isNull(scheduleDetails)) {
            return success(0);
        } else {
            return success(scheduleDetails);
        }
    }

    /**
     * 结束项目
     *
     * @param id 项目主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/endProject/{id}")
    public AjaxResult endProject(@PathVariable("id") Long id) {
        MoeProject moeProject = moeProjectService.selectMoeProjectById(id);
        if (MoeProjectStatus.APPROVED.getValue().equals(moeProject.getStatus())) {
            return warn("该项目已完成验收");
        } else if (MoeProjectStatus.FINISHED.getValue().equals(moeProject.getStatus())) {
            return warn("该项目已结束");
        } else if (MoeProjectStatus.SUBMITTED.getValue().equals(moeProject.getStatus())) {
            return warn("该项目等待审批");
        }
        try {
            return toAjax(moeProjectService.endProject(id));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 获取项目的顶级任务列表
     *
     * @param id 项目主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/getTopTaskList/{id}")
    public TableDataInfo getTopTaskList(@PathVariable("id") Long id) {
        startPage();
        List<MoeTask> list = moeProjectService.getTopTaskList(id);
        return getDataTable(list);
    }

    /**
     * 获取处在预警期的项目
     *
     * @return 结果
     */
    @PreAuthorize("@ss.hasRole('project-manager')")
    @GetMapping(value = "/getWarnProjectList")
    public TableDataInfo getWarnProjectList() {
        Long userId = SecurityUtils.getUserId();
        startPage();
        List<MoeProject> list = moeProjectService.getWarnProjectListByManagerId(userId);
        return getDataTable(list);
    }

}
